import { SvgIcon } from '@/components/icon';
import { message } from 'antd';
import React, { useEffect, useState } from 'react';
import Tables from '@/components/tables/tables';
import PagesHeader from '@/components/pages-header';
import NotData from '@/components/NotData';
import knowService from '@/api/services/knowService';
import { useParams } from '@/router/hooks';
import { Search } from '@/components/eai-design';
import DislikeDisposeModal from './dislikeDisposeModal';
import useModal from '@/hooks/use-modal/useModal';
import { useKnowledgeStore } from '@/store/knowledge';
import { BaseQuestionType } from '@/types/know/know';
import TipDesc from '@/components/tipDesc/tipDesc';

const UserDislike: React.FC = () => {
  const modal = useModal('dispose');
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [search, setSearch] = useState('');
  const [total, setTotal] = useState(0);
  const { appId = '' } = useParams() as { appId: string };
  const [paginationProps, setPaginationProps] = useState({
    page: 1,
    pageSize: 10,
    searchText: '',
    offset: 0,
    appId: appId,
  });
  const { setDislikeItem, dislikeItem } = useKnowledgeStore();
  const [dislikeList, setDislikeList] = useState<BaseQuestionType[]>([]);
  const [overlookItem, setOverlookItem] = useState<BaseQuestionType[]>();

  useEffect(() => {
    getList();
  }, [paginationProps, dislikeItem]);

  const getList = async () => {
    try {
      const res = await knowService.getUserDislikeList(paginationProps);
      setDislikeList(res.list || []);
      setTotal(res.total || 0);
    } catch (error) {
      message.error(error as string);
    }
  };

  // 列定义
  const columns = [
    {
      title: <span>用户点踩问题</span>,
      dataIndex: 'keyQuestionText',
      key: 'keyQuestionText',
      render: (text: string) => (
        <div className="w-[600px] truncate" title={text}>
          {text}
        </div>
      ),
      width: 300,
    },
    {
      title: <span>操作</span>,
      key: 'action',
      width: 200,
      render: (_: any, record: any) => (
        <div className="flex  gap-4">
          <a
            className="flex cursor-pointer items-center text-@brand-color"
            onClick={() => {
              modal.dispose.open();
              setDislikeItem(record);
            }}
          >
            <SvgIcon icon="edit" size="16" className="mr-1" />
            处理
          </a>
          <a
            className="flex cursor-pointer items-center text-@error-color"
            onClick={() => {
              handleOverlook([record]);
            }}
          >
            <SvgIcon icon="message-ic21" size="16" className="mr-1" />
            忽略
          </a>
        </div>
      ),
    },
  ];

  // 分页切换
  const handlePageChange = (page: number, pageSize?: number) => {
    setPaginationProps((prev) => ({
      ...prev,
      page,
      pageSize: pageSize || prev.pageSize,
      offset: (page - 1) * (pageSize || prev.pageSize),
    }));
  };

  // 搜索
  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(e.target.value);
    setPaginationProps((prev) => ({
      ...prev,
      searchText: e.target.value,
      page: 1,
      offset: 0,
    }));
  };
  //忽略
  const handleOverlook = async (items?: BaseQuestionType[]) => {
    try {
      const targetItems = items || overlookItem;
      const promises = targetItems?.map(async (item) => {
        await onIgnore(item);
      });
      await Promise.all(promises || []);
      message.success('忽略成功');
      setSelectedRowKeys([]);
      getList();
    } catch (error) {
      message.error(error as string);
    }
  };

  const onIgnore = async (data: BaseQuestionType) => {
    try {
      await knowService.postMarkQuestion({
        id: data?._id || data?.keyQuestionId,
        appId,
        datas: [
          {
            q: data?.keyQuestionText,
            a: data?.keyQuestionAnswer,
            question_id: data?.keyQuestionId,
          },
        ],

        is_ignore: true,
        type: 'feedback',
      });
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <div className="flex h-full flex-col bg-white">
      <PagesHeader>
        用户点踩问题
        <TipDesc
          title="针对用户在问答过程中不满意的回答，提供治理机制，支持自定义问题与答案（FAQ）对的维护与优化。"
          className="!my-0"
        />
      </PagesHeader>
      <div className="flex flex-1 flex-col rounded-default px-5">
        <div className="my-4 flex items-center justify-between">
          <div>
            <Search value={search} onChange={handleSearch} placeholder="搜索" />
          </div>
          <div className="flex items-center">
            <div
              className={`ml-4 flex h-[32px] w-[68px]  items-center justify-center rounded-md border ${
                selectedRowKeys.length > 0
                  ? 'cursor-pointer !border-@brand-color !text-@brand-color'
                  : 'cursor-not-allowed !border-@brand-color-disabled !text-@brand-color-disabled'
              }`}
              onClick={() => {
                if (selectedRowKeys.length > 0) {
                  handleOverlook();
                }
              }}
            >
              <SvgIcon icon="message-ic21" size="20" className="mr-1" />
              忽略
            </div>
          </div>
        </div>
        {/* 表格内容 */}
        <div className="flex flex-1 flex-col">
          {dislikeList.length > 0 ? (
            <Tables
              rowSelection={{
                type: 'checkbox',
                selectedRowKeys,
                onChange: (selectedRowKeys: React.Key[]) => {
                  setSelectedRowKeys(selectedRowKeys);
                  const selectedItems = dislikeList.filter((item) =>
                    selectedRowKeys.includes(item.qaId || ''),
                  );
                  setOverlookItem(selectedItems);
                },
              }}
              rowKey="qaId"
              columns={columns}
              dataSource={dislikeList}
              pagination={false}
              className="border border-gray-100"
              paginationProps={{
                total: total,
                current: paginationProps.page,
                pageSize: paginationProps.pageSize,
                onChange: handlePageChange,
              }}
            />
          ) : (
            <NotData />
          )}
        </div>
      </div>

      <DislikeDisposeModal
        open={modal.dispose.isOpen}
        onCancel={() => modal.dispose.close()}
        onOk={() => {
          modal.dispose.close();
          getList();
        }}
        onOverlook={() => {
          handleOverlook([dislikeItem]);
          modal.dispose.close();
        }}
      />
    </div>
  );
};

export default UserDislike;
